package com.sx.micowell.framework.model

import android.annotation.SuppressLint
import android.text.TextUtils
import androidx.databinding.ObservableField
import com.example.mvvm.base.vm.BaseViewModel
import com.example.mvvm.event.SingleLiveEvent
import com.example.mvvm.rx.RxBus
import com.example.mvvm.until.LogUtils
import com.example.mvvm.until.SPUtils
import com.example.mvvm.until.ToastUtils
import com.google.gson.Gson
import com.miloyu.modelnet.network.ApiResponse
import com.miloyu.modelnet.network.HttpClient
import com.miloyu.modelnet.network.tools.RxUtils
import com.miloyu.modelnet.response.TokenVO
import com.sx.micowell.framework.app.AppConstant
import com.sx.micowell.framework.app.SPKey
import com.sx.micowell.framework.arouth.RouteManager
import com.sx.micowell.framework.binding.BindingCommand
import com.sx.micowell.framework.binding.impl.IBindingAction
import com.sx.micowell.framework.binding.impl.IBindingConsumer
import com.sx.micowell.framework.entity.AccountBean
import com.sx.micowell.framework.tools.EventInfo
import com.sx.micowell.framework.tools.setDataList
import io.reactivex.android.schedulers.AndroidSchedulers

/**
 * @author: YY
 * @time: 2021/8/3
 * @describe TODO
 */
class VerifyCodeModel : BaseViewModel() {

    override fun registerRxBus() {
        super.registerRxBus()
        addSubscribe(
            RxBus.getDefault().toObservable(EventInfo::class.java)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe { event ->
                    if (event.type == AppConstant.EVENT_REGISTER_PWD_SUCCESS) {
                        // 注册成功、修改密码成功
                        context.finishEvent.call()
                    }
                }
        )
    }


    // 类型
    var type: Int = 0

    // 手机号
    var phone: String = ""

    // openID
    var openId: String = ""

    var bindSuccessEvent: SingleLiveEvent<Void> = SingleLiveEvent()

    // 手机号
    var phoneNumberData = ObservableField("")

    // 验证码
    var verifyCodeData = ObservableField("")

    //发送验证码
    var sendCodeEvent: SingleLiveEvent<Void> = SingleLiveEvent()

    fun setPhoneNumber(data: String, type: Int, openId: String) {
        LogUtils.d("setPhoneNumber $data === $openId")
        phoneNumberData.set(data)
        this.type = type
        this.phone = data
        this.openId = openId

//        sendSmsCode(type, data)
    }

    fun setVerifyCode(code: String) {
        LogUtils.d("setVerifyCode $code")
        verifyCodeData.set(code)
    }

    // 下一步
    val nextStepOnClickCommand = BindingCommand<Any>(IBindingAction {
        when {
            TextUtils.isEmpty(verifyCodeData.get()) -> {
                ToastUtils.showShort("验证码不能为空！")
            }
            verifyCodeData.get().toString().length < 4 -> {
                ToastUtils.showShort("请填写完整的验证码！")
            }
            else -> {
                checkVCode(verifyCodeData.get().toString(), phoneNumberData.get().toString())

            }
        }
    })

    fun checkVCode(verCode: String, phone: String) {
        HttpClient.instance.apiService
            .checkVCode(phone, verCode)
            .doOnSubscribe { ui.showDialog() }
            .compose(RxUtils.compose())
            .subscribeWith(object : ApiResponse<Void>() {

                override fun success(data: Void?, msg: String?) {
                    ui.hideDialog()
                    if (type == -1) {
                        bindPhone()
                    } else {
                        RouteManager.getInstance().intentSetupPwd(
                            phoneNumberData.get().toString(), verifyCodeData.get().toString(), type
                        )
                    }
                }

                override fun onFail(e: Throwable?, errorMsg: String?) {
                    ui.hideDialog()
                    ToastUtils.showShort("$errorMsg")
                }

            })
    }

    @SuppressLint("CheckResult")
    fun sendSmsCode(type: Int, phone: String) {
        if (type == 0 || type == -1) {
            HttpClient.instance.apiService
                .sendRegisterSms(phone)
                .doOnSubscribe { ui.showDialog() }
                .compose(RxUtils.compose())
                .subscribeWith(object : ApiResponse<Void>() {

                    override fun success(data: Void?, msg: String?) {
                        ui.hideDialog()
                        ToastUtils.showShort("$msg")
                        sendCodeEvent.call()
                    }

                    override fun onFail(e: Throwable?, errorMsg: String?) {
                        ui.hideDialog()
                        ToastUtils.showShort("$errorMsg")
                    }

                })

        } else {
            HttpClient.instance.apiService
                .sendModifySms(phone)
                .doOnSubscribe { ui.showDialog() }
                .compose(RxUtils.compose())
                .subscribeWith(object : ApiResponse<Void>() {

                    override fun success(data: Void?, msg: String?) {
                        ui.hideDialog()
                        ToastUtils.showShort("$msg")
                        sendCodeEvent.call()
                    }

                    override fun onFail(e: Throwable?, errorMsg: String?) {
                        ui.hideDialog()
                        ToastUtils.showShort("$errorMsg")
                    }

                })

        }
    }

    fun bindPhone() {
        addSubscribe(
            HttpClient.instance.apiService
                .bindPhone(openId, phone, verifyCodeData.get().toString())
                .compose(RxUtils.compose())
                .subscribeWith(object : ApiResponse<TokenVO>() {

                    override fun success(data: TokenVO?, msg: String?) {
                        ui.hideDialog()
                        ToastUtils.showShort("绑定成功")
                        SPUtils.getInstance().put(SPKey.SP_TOKEN, data?.token.toString())
                        SPUtils.getInstance().put(SPKey.SP_PHONE, phone)
                        saveAccount(phone, "", data?.token.toString())
                        bindSuccessEvent.call()
                    }

                    override fun onFail(e: Throwable?, errorMsg: String?) {
                        ui.hideDialog()
                        ToastUtils.showShort("$errorMsg")
                    }

                })
        )
    }


    fun saveAccount(phone: String, pwd: String, token: String) {
        val accountBean = AccountBean(phone, pwd, token)

        if (!TextUtils.isEmpty(SPUtils.getInstance().getString(SPKey.SP_ACCOUNT))) {
            val array: Array<AccountBean> = Gson().fromJson(
                SPUtils.getInstance().getString(SPKey.SP_ACCOUNT), Array<AccountBean>::class.java
            )
            val list = array.toMutableList()
            list.add(0, accountBean)
            setDataList(SPKey.SP_ACCOUNT, list.distinct())
        } else {
            val classTests = mutableListOf<AccountBean>()
            classTests.add(accountBean)
            setDataList(SPKey.SP_ACCOUNT, classTests)
        }
    }
}